package interview.blockqueue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share {
    public int a = 0;
    private Lock lock = new ReentrantLock();
    Condition condation = lock.newCondition();

    public void increase() {
        lock.lock();
        try {
            while (a != 0) {
                condation.await();
            }
            a = a + 1;
            System.out.println(Thread.currentThread().getName() + ":" + a);
            condation.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();

        }finally {
            lock.unlock();
        }
    }

    public void decrease() {
        lock.lock();
        try {
            while (a == 0) {
                condation.await();
            }
            a = a - 1;
            System.out.println(Thread.currentThread().getName() + ":" + a);
            condation.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

public class LockConsumerAndProduct {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(()->{
            for(int i=0;i<5;i++) {
                share.increase();

            }

        },"AAA").start();

        new Thread(()->{
            for(int i=0;i<5;i++) {
                share.decrease();
            }
        },"BBB").start();
        new Thread(()->{
            for(int i=0;i<5;i++) {
                share.decrease();
            }
        },"BBB").start();
    }
}
